import React, { Component } from "react";

import {
  get_City_List,
  get_Hot_City,
  get_Current_City,
} from "../../utils/biz_http.js";

import { NavBar, Toast } from "antd-mobile";

import { AutoSizer, List } from "react-virtualized";

import "./citylist.scss";
import "../../assets/fonts/iconfont.css";
import "../../../node_modules/react-virtualized/styles.css";

class CityList extends Component {
  constructor(props) {
    super(props);
    this.cityIndexComponent = React.createRef();
  }
  state = {
    activeIndex: 0,
    cityList: {},
    cityIndex: [],
  };

  async componentDidMount() {
    await this.getCityList();
    /**
     * 让list控件预渲染计算出每一行的高度,但是直接执行会抛出错误：
     * CellSizeAndPositionManager.js:83 Uncaught Error: Requested index -1 is outside of range 0..0
     * 原因：执行measureAllRows方式时，citylist数据还没有响应回来，所以默认拿到的是-1
     * 解决：改为数据响应回来以后再执行
     *  */
    this.cityIndexComponent.current.measureAllRows();
  }

  async getCityList() {
    try {
      // 获取城市数据
      let res = await get_City_List();
      //   获取热门城市数据
      let hotcity = await get_Hot_City();
      // 获取当前城市
      let currentCity = await get_Current_City();
      //   console.log(res.data.body);
      this.getCityData(res.data.body, hotcity.data.body, currentCity);
    } catch (e) {}
  }

  getCityData(list, hotcity, currentCity) {
    /**list 中的每一个item数据格式 
         *{
                "label": "北京",
                "value": "AREA|88cff55c-aaa4-e2e0",
                "pinyin": "beijing",
                "short": "bj"
                },
         */
    console.log(hotcity);
    let cityList = {
      "#": [{ label: currentCity.label, value: "#" }],
      "#热": hotcity,
    };
    let cityIndex = [];
    list.forEach((item) => {
      let index_char = item.short.slice(0, 1);
      if (!cityList[index_char]) {
        cityList[index_char] = [item];
      } else {
        cityList[index_char].push(item);
      }
    });

    cityIndex = Object.keys(cityList).sort();
    console.log(JSON.stringify(cityList));
    this.setState({
      cityList,
      cityIndex,
    });
  }

  // 格式化索引
  formatIndex = (indexvalue) => {
    if (indexvalue === "#") {
      return "当前城市";
    } else if (indexvalue === "#热") {
      return "热门城市";
    } else {
      return indexvalue.toUpperCase();
    }
  };

  // 用户选择城市时触发点击事件
  selectCity = (item) => {
    const HOT_CITYS = ["北京", "上海", "广州", "深圳"];
    let { label, value } = item;
    if (HOT_CITYS.indexOf(label) <= -1) {
      Toast.info(`${label}没有房源信息，请重新选择`, 0.8);
      return;
    }
    localStorage.setItem("cur_city", JSON.stringify({ label, value }));
    this.props.history.go(-1);
  };

  // 渲染行数据
  rowRender = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style, // Style object to be applied to row (to position it)
  }) => {
    let cityList = this.state.cityList;
    let cityIndex = this.state.cityIndex;
    return (
      <div key={key} style={style} className="item">
        <div className="itemIndex">{this.formatIndex(cityIndex[index])}</div>
        {/* <div className="itemIndex">G</div>
            <div className="itemName">广州</div> */}
        {cityList[cityIndex[index]].map((item) => (
          <div
            className="itemName"
            key={item.value}
            onClick={() => {
              this.selectCity(item);
            }}
          >
            {item.label}
          </div>
        ))}
      </div>
    );
  };

  // 动态计算每一行高度
  rowHeight = ({ index }) => {
    /*
           索引所在div高度：36
           城市所在div高度：50
        公式:  总高度= 索引所在div高度 + this.state.cityList[this.state.cityIndex[index]].length * 50
         */
    return 36 + this.state.cityList[this.state.cityIndex[index]].length * 50;
  };

  // 右边索引
  rightIndex = () => {
    return (
      <div className="rightindex">
        <ul>
          {this.state.cityIndex.map((item, index) => (
            <li
              key={item}
              className={this.state.activeIndex === index ? "active" : ""}
              onClick={() => {
                this.cityIndexComponent.current.scrollToRow(index);
              }}
            >
              {item === "#热" ? "热" : item.toUpperCase()}
            </li>
          ))}
        </ul>
      </div>
    );
  };

  // 设置列表滚动时自动选中右边城市索引项
  onRowsRendered = ({
    overscanStartIndex,
    overscanStopIndex,
    startIndex, // 表示列表滚动到最上面一行的索引号
    stopIndex,
  }) => {
    if (startIndex !== this.state.activeIndex) {
      this.setState({
        activeIndex: startIndex,
      });
    }
  };

  render() {
    // console.log(this.state.cityIndex, this.state.cityList);
    return (
      <div className="citylist">
        {/* 顶部导航 */}
        <NavBar
          mode="light"
          //   icon={<Icon type="left" />}
          icon={<i className="iconfont icon-back"></i>}
          onLeftClick={() => this.props.history.go(-1)}
        >
          城市选择
        </NavBar>
        {/* 城市列表 */}
        <AutoSizer>
          {/* 注意：AutoSizer会找父元素的高和宽 */}
          {({ height, width }) => (
            <List
              ref={this.cityIndexComponent}
              width={width}
              height={height}
              rowCount={this.state.cityIndex.length}
              rowHeight={this.rowHeight}
              rowRenderer={this.rowRender}
              onRowsRendered={this.onRowsRendered} //设定滚动时自动选择右边索引
              scrollToAlignment="start" // 解决scrollToRow(index)定位不准确问题，将当前项自动精确滚动到顶部
            />
          )}
        </AutoSizer>

        {/* 右边索引列表 */}
        {this.rightIndex()}
      </div>
    );
  }
}

export default CityList;
